<?php

namespace App\Http\Controllers\DingDropOff;

use App\Http\Controllers\Controller;
use App\Models\Mileage\MileageDrop;
use App\Models\Role;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class DingDropOffController extends Controller
{
    public $roleId;
    public $roleName;
    public $userId;
    public $userName;

    public function getSeeIds($userId): void
    {
        if ($userId) {
            $userInfo = User::query()->where('ding_user_id', $userId)->first();
            if ($userInfo) {
                $this->roleId = $userInfo['group_id'];
                // $this->roleName = Role::query()->where('id', $userInfo['group_id'])->first()->name;
                $roleId = DB::table('sys_roles_users')->where('user_id', $userInfo['id'])->pluck('role_id')->toArray();
                $this->roleName = Role::query()->whereIn('id', $roleId)->pluck('name')->toArray();
                $this->userId = $userInfo['id'];
                $this->userName = $userInfo['name'];
            }
        }
    }

    /**
     * 掉趟列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function dropTripList(Request $request)
    {
        $params = $request->all();
        $this->getSeeIds($params['ding_user_id']);

        if ($params['date'][0] === null && $params['date'][1] === null) {
            $params['date'] = [];
        } else {
            $date = $params['date'];
            $params['date'] = [
                date('Y-m-d', strtotime($date[0])),
                date('Y-m-d', strtotime($date[1])),
            ];
        }
        $data = $this->getMileageDropList($params)->orderByDesc('date')->get()->toArray();

        $data = collect($data)->groupBy('created_at')->toArray();

        $data = $this->transData($data);

        return response()->formatJson($data);
    }

    public function getMileageDropList($params): Builder
    {
        $query = MileageDrop::query();

        if (isset($params['bus_num'])) {
            $query->where('bus_num', 'like', '%'.$params['bus_num'].'%');
        }

        if ($params['date']) {
            $query->whereBetween('date', [$params['date']]);
        }

        if (isset($params['page_number'], $params['page_size'])) {
            $query
                ->limit($params['page_size'])
                ->offset(($params['page_number'] - 1) * $params['page_size']);
        }

        return $query->where('user_id', $this->userId);
    }

    public function transData($params)
    {
        $data = [];
        foreach ($params as $dateTime => $items) {
            $detail = [];
            foreach ($items as $item) {
                $detail[] = [
                    'id'        => $item['id'],
                    'bus_num'   => str_replace('陕G', '', $item['bus_num']),
                    'drop_trip' => $item['drop_trip'],
                    'reason'    => json_decode($item['reason'], true),
                    'remark'    => $item['remark'],
                ];
            }
            $data[] = [
                'date'       => $items[0]['date'],
                'detail'     => $detail,
                'created_at' => $dateTime,
            ];
        }

        return $data;
    }

    /**
     * 保存掉趟
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function storeDropTrip(Request $request)
    {
        $params = $request->all();
        $params['date'] = date('Y-m-d', strtotime($params['date']));
        $this->getSeeIds($params['ding_user_id']);
        $insertData = [];
        $dateTime = date('Y-m-d H:i:s');
        if (isset($params['detail'])) {
            foreach ($params['detail'] as $k => $v) {
                $insertData[] = [
                    'date'       => $params['date'],
                    'bus_num'    => str_replace('陕G', '', $v['bus_num']),
                    'drop_trip'  => $v['drop_trip'],
                    'reason'     => isset($v['reason']) ? json_encode(explode(',', $v['reason'])) : '',
                    'remark'     => isset($v['remark']) ? $v['remark'] : '',
                    'user_id'    => $this->userId,
                    'created_at' => $dateTime,
                ];
            }
        }

        $result = MileageDrop::query()->insert($insertData);
        $message = $result ? '添加成功' : '添加失败';

        return response()->formatJson($result, $message);
    }

    public function deleteDropTrip(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = $request['ids'];
            $delCount = MileageDrop::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 保存掉趟
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function isBusNum(Request $request)
    {
        $params = $request->all();
        if ($params['bus_num']) {
            // 删除陕G
            $params['bus_num'] = Str::of($params['bus_num'])->replace('陕G', '');
            $bus_data = DB::table('akbus_bus_distribution')
                ->where('date', '<=', date('Y-m-d'))
                ->where('end_date', '>=', date('Y-m-d'))
                ->pluck('license_plate_num')
                ->toArray();
            if (in_array($params['bus_num'], $bus_data)) {
                $result = true;
            } else {
                $result = false;
            }
        } else {
            $result = false;
        }
        $message = $result ? '车牌号存在' : '车牌号不存在';

        return response()->formatJson($result, $message);
    }
}
